package com.heima.search.service;


import com.heima.common.search.ElasticSearchTemplate;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.dtos.UserSearchDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import rx.Completable;

import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private ElasticSearchTemplate elasticSearchTemplate;


    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
       if (dto ==null || StringUtils.isBlank(dto.getSearchWords())){
           return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);//无效的参数；判断用户参数的参数是否为空
       }

       //提取入参
        int pageNum = dto.getPageNum();
        int pageSize = dto.getPageSize();
        String searchWords = dto.getSearchWords();
        Date minBehotTime = dto.getMinBehotTime();

        //查询关键字

        QueryStringQueryBuilder stringQueryBuilder = elasticSearchTemplate.getStringQueryBuilder(searchWords, Operator.OR, "title", "content");

        //时间范围查询
        Map<String,Object> rangeCondition = new HashMap<>(1);
        RangeQueryBuilder rangeQueryBuilder = (RangeQueryBuilder) elasticSearchTemplate.getRangeBuilder("publishTime", rangeCondition);

        //布尔查询
        Map<String, AbstractQueryBuilder> boolCondition = new HashMap<>();
        boolCondition.put("must",stringQueryBuilder);
        boolCondition.put("filter",stringQueryBuilder);
        BoolQueryBuilder boolQueryBuilder = elasticSearchTemplate.getBoolQueryBuilder(boolCondition);

        //高亮
        HighlightBuilder highlightBuilder = elasticSearchTemplate.getHighlightBuilder("title", "<font style='color: red; font-size: inherit;'>", "</font>");

        //执行查询
        SearchResponse response = elasticSearchTemplate.search("app_info_article", boolQueryBuilder, highlightBuilder, pageNum, pageSize, "publishTime", SortOrder.DESC);

        //提取结果
        SearchHit[] hits = response.getHits().getHits();
        List<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            Map<String,Object> sourceAsMap = hit.getSourceAsMap();

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();

            if (!CollectionUtils.isEmpty(highlightFields)){
                Text[] titles = highlightFields.get("title").getFragments();
                String join = StringUtils.join(titles, ",");
                sourceAsMap.put("h_title",join);
            }else {
                sourceAsMap.put("h_title",sourceAsMap.get("title"));
            }
            list.add(sourceAsMap);
        }



        return ResponseResult.okResult(list);
    }
}

























